package com.cbgolf.oa.model;

import android.support.v4.util.ArrayMap;
import com.cbgolf.oa.base.BaseModel;
import com.cbgolf.oa.entity.MenuBean;
import com.cbgolf.oa.entity.Menus;
import com.cbgolf.oa.entity.MessageBean;
import com.cbgolf.oa.entity.NetResponse;
import com.cbgolf.oa.entity.ParkBean;
import com.cbgolf.oa.event.EventMenus;
import com.cbgolf.oa.event.EventMsg;
import com.cbgolf.oa.event.EventOrder;
import com.cbgolf.oa.event.EventPark;
import com.cbgolf.oa.inteface.IAsynTask;
import com.cbgolf.oa.manager.DataManager;
import com.cbgolf.oa.net.NetCallBack;
import com.cbgolf.oa.net.NetUtils;
import com.cbgolf.oa.net.Web;
import com.cbgolf.oa.net.WebAPI;
import com.cbgolf.oa.presenter.IMainPresenter;
import com.cbgolf.oa.presenter.IMainPresenter.IMainModel;
import com.cbgolf.oa.user.User;
import com.cbgolf.oa.user.UserData;
import com.cbgolf.oa.util.DataUtil;
import com.cbgolf.oa.util.TextUtil;
import com.cbgolf.oa.util.Util;
import com.cbgolf.oa.viewbean.OrderBean;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import org.greenrobot.eventbus.EventBus;

/**
 * @author lq
 * @date 2017/11/3
 */

public class MainModel extends BaseModel implements IMainModel {

  private List<MenuBean> listMenuBack = new ArrayList<>();
  private List<Menus> ListStatistics = new ArrayList<>();
  private List<Menus> ListPermission = new ArrayList<>();
  private List<Menus> ListBusiness = new ArrayList<>();


  private IMainPresenter worker;

  public MainModel(IMainPresenter worker) {
    this.worker = worker;
  }


  public void getUserInfo() {
    if (Util.isNull(DataUtil.getToken())) {
      return;
    }
    Web.getOK(WebAPI.user_info_get,
        new NetCallBack(response -> {
          if (NetUtils.SUCCESS != response.statusCode) {
            return;
          }
          try {
            UserData.upDataUser((User) getBean(response, User.class));
            worker.setUserInfo();
          } catch (Exception e) {
          }
        }));
  }

  public void getShowModel(boolean isOnce) {
    if (isOnce) {
      worker.showProgress();
    }
    Web.getOK(WebAPI.my_permissions_select_get, new NetCallBack(response -> {
      worker.stopProgress();
//      if (!isResOk(response)) {
//        worker.getDataFail(errorMsg);
//        return;
//      }
      List<Menus> list = getList(response, Menus.class);
//      if (Util.listIsNull(list)) {
//        worker.getDataFail(ErrorUtil.NODATA);
//        return;
//      }
//      filterList(list);
      hasOrderConfirmPermission = false;
      if (!Util.isNull(list)) {
        filterList(response, list);
      } else {
        backMenusResult(response, null);
      }

    }));
  }

  private void backMenusResult(NetResponse response, List<MenuBean> listMenuBack) {
    EventBus.getDefault().post(new EventMenus.Builder()
        .setTarget(DataManager.MENUS_MAIN)
        .setListMenus(listMenuBack)
        .setHasOrderConfirmPermission(hasOrderConfirmPermission)
        .setError(response.errorMsg, errorCode)
        .build());
  }

  private boolean hasOrderConfirmPermission;

  private void filterList(NetResponse response, final List<Menus> list) {
    ListStatistics.clear();
    ListPermission.clear();
    ListBusiness.clear();
    listMenuBack.clear();
    Util.asynTask(new IAsynTask() {
      @Override
      public void updateUI(Serializable ser) {
        MenuBean bean;
        if (!Util.listIsNull(ListStatistics)) {
          bean = new MenuBean();
          bean.typeName = DataManager.MUNE_TYPES_TITLES[0];
          bean.list = ListStatistics;
          listMenuBack.add(bean);
        }
        if (!Util.listIsNull(ListPermission)) {
          bean = new MenuBean();
          bean.typeName = DataManager.MUNE_TYPES_TITLES[1];
          bean.list = ListPermission;
          listMenuBack.add(bean);
        }
        if (!Util.listIsNull(ListBusiness)) {
          bean = new MenuBean();
          bean.typeName = DataManager.MUNE_TYPES_TITLES[2];
          bean.list = ListBusiness;
          listMenuBack.add(bean);
        }
        backMenusResult(response, listMenuBack);

      }

      @Override
      public Serializable Run() {
        Menus bean;
        List<Menus> listMenus = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
          if (null == list.get(i) || null == list.get(i).data
              || null == list.get(i).data.menu) {
            continue;
          }
          if (!TextUtil.contains(list.get(i).data.menu.title, DataManager.OA_MENUS)) {
            continue;
          }
          if (TextUtil
              .contains(list.get(i).data.menu.menuId, DataManager.ORDER_CONFIRM_PERMISSION)) {
            hasOrderConfirmPermission = true;
          }
          for (int j = 0; j < DataManager.MUNE_IDS.length; j++) {
            if (TextUtil.contains(list.get(i).data.menu.menuId, DataManager.MUNE_IDS[j])) {
              bean = new Menus();
              bean.modelId = list.get(i).data.menu.menuId;
              listMenus.add(bean);
              break;
            }
          }

        }
        if (!Util.listIsNull(listMenus)) {
          for (int j = 0; j < DataManager.MUNE_STATISTICS_IDS.length; j++) {
            for (int i = 0; i < listMenus.size(); i++) {
              if (TextUtil.contains(listMenus.get(i).modelId, DataManager.MUNE_STATISTICS_IDS[j])) {
                ListStatistics.add(listMenus.get(i));
              }
            }
          }
          for (int j = 0; j < DataManager.MUNE_PERMISSION_IDS.length; j++) {
            for (int i = 0; i < listMenus.size(); i++) {
              if (TextUtil.contains(listMenus.get(i).modelId, DataManager.MUNE_PERMISSION_IDS[j])) {
                ListPermission.add(listMenus.get(i));
              }
            }
          }
          for (int j = 0; j < DataManager.MUNE_BUSINESS_IDS.length; j++) {
            for (int i = 0; i < listMenus.size(); i++) {
              if (TextUtil.contains(listMenus.get(i).modelId, DataManager.MUNE_BUSINESS_IDS[j])) {
                ListBusiness.add(listMenus.get(i));
              }
            }
          }

        }
        return null;
      }
    });
  }

  public void getMsgCount() {
    Map<String, String> map = new ArrayMap<>();
    map.put("pageSize", pageSize + "");
    map.put("messageType", "");
    map.put("currentPage", "0");
    Web.getOK(WebAPI.message_all_get, map, new NetCallBack(response -> {
      List<MessageBean> list = getList(response, MessageBean.class);
      EventBus.getDefault().post(new EventMsg.Builder()
          .setTarget(DataManager.MESSAGE_NO_READ)
          .setHaveNotRead(!Util.listIsNull(list) && list.get(0).haveNotRead)
          .build());
    }));
  }

  public void getFirWayLatlon() {
    Web.getOK(WebAPI.park_map_latlon_get, new NetCallBack(response -> {
      EventBus.getDefault().post(new EventPark.Builder()
          .setTarget(DataManager.PARK_MAP_LATLON_MAIN)
          .setParkBean((ParkBean) getBean(response, ParkBean.class))
          .setError(errorMsg, errorCode)
          .build());
    }));
  }

  @Override
  public void confirmOrder(String orderId, String orderCode) {
    Map<String, String> map = new ArrayMap<>();
    map.put("orderId", orderId);
    map.put("code", orderCode);
    worker.showProgress();
    Web.getOK(WebAPI.order_confirm_post, map, new NetCallBack(response -> {
      EventBus.getDefault().post(new EventOrder.Builder()
          .setOrderBean((OrderBean) getBean(response, OrderBean.class))
          .setIsConfirmSuccess(response.statusCode == NetUtils.SUCCESS)
          .setError(response.errorMsg, errorCode)
          .setTarget(DataManager.ORDER_CONFIRM_BYQR)
          .build());
    }));
  }
}
